package com.xmg.unsafe;

import sun.misc.Unsafe;

public class TestAtomicInteger {
}

class MyAtomicInteger {
    private volatile int value;
    private static final long valueOffset;
    static final Unsafe unsafe;
    static {
        unsafe = UnSafeAccess.getUnsafe();
        try {
            valueOffset = unsafe.objectFieldOffset(MyAtomicInteger.class.getDeclaredField("value"));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    public int getValue(){
        return value;
    }

    public void decrement(int amount){
        while (true) {
            int prev = this.value;
            int next = this.value - amount;
            if (unsafe.compareAndSwapInt(this, valueOffset, prev, next)) {
                break;
            }
        }
    }
}
